package com.bai.ks2022.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String userSQL = "select username,password,valid from common " + "where username = ?";
        String authoritySQL="select c.username,a.admin from common c, " + "admin a,common_admin ca where " +
                "ca.common_id and ca.admin_id=a.id and c.username=?";
        auth.jdbcAuthentication().passwordEncoder(encoder)
                .dataSource(dataSource)
                .usersByUsernameQuery(userSQL)
                .authoritiesByUsernameQuery(userSQL)
                .authoritiesByUsernameQuery(authoritySQL);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/login/**").permitAll()
                .antMatchers("/common/**").hasRole("common")
                .antMatchers("/admin/**").hasRole("admin")
                .anyRequest().authenticated();

        http.formLogin()
                .loginPage("/login").permitAll()
                .usernameParameter("name").passwordParameter("pwd")
                .defaultSuccessUrl("/index")
                .failureUrl("/login?error");

//        http.logout()
//                .logoutUrl("/login")
//                .logoutSuccessUrl("/");
    }

}

